#import "RRDialog.h"
#import "RRLoginDialog.h"

@implementation RRLoginDialog


- (id)initWithURL:(NSString*) loginURL 
      loginParams:(NSMutableDictionary*) params 
         delegate:(id <RRLoginDialogDelegate>) delegate{
  
  self = [super init];
  _serverURL = [loginURL retain];
  _params = [params retain];
  _loginDelegate = delegate;
  return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// RRDialog

- (void) dialogDidSucceed:(NSURL*)url {
  NSString *q = [url absoluteString];
  NSString *token = [self getStringFromUrl:q needle:@"access_token="];
  NSString *expTime = [self getStringFromUrl:q needle:@"expires_in="];
  NSDate *expirationDate =nil;
  
  if (expTime != nil) {
    int expVal = [expTime intValue];
    if (expVal == 0) {
      expirationDate = [NSDate distantFuture];
    } else {
      expirationDate = [NSDate dateWithTimeIntervalSinceNow:expVal];
    } 
  } 
  
  if ((token == (NSString *) [NSNull null]) || (token.length == 0)) {
    [self dialogDidCancel:url];
    [self dismissWithSuccess:NO animated:YES];
  } else {
    if ([_loginDelegate respondsToSelector:@selector(rrDialogLogin:expirationDate:)]) {
      [_loginDelegate rrDialogLogin:token expirationDate:expirationDate];
    }
    [self dismissWithSuccess:YES animated:YES];
  }
  
}


- (void)dialogDidCancel:(NSURL *)url {
  [self dismissWithSuccess:NO animated:YES];
  if ([_loginDelegate respondsToSelector:@selector(rrDialogNotLogin:)]) {
    [_loginDelegate rrDialogNotLogin:YES];
  }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  if (!(([error.domain isEqualToString:@"NSURLErrorDomain"] && error.code == -999) ||
        ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102))) {
    [super webView:webView didFailLoadWithError:error];
    if ([_loginDelegate respondsToSelector:@selector(rrDialogNotLogin:)]) {
      [_loginDelegate rrDialogNotLogin:NO];
    }
  }
}

/**
 * 
 * 解析 url 参数的function
 */
- (NSDictionary*)parseURLParams:(NSString *)query {
	NSArray *pairs = [query componentsSeparatedByString:@"&"];
	NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
	for (NSString *pair in pairs) {
		NSArray *kv = [pair componentsSeparatedByString:@"="];
		NSString *val =
		[[kv objectAtIndex:1]
		 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		
		[params setObject:val forKey:[kv objectAtIndex:0]];
	}
	return params;
}

/**
 *  点关闭或提交表单时，进行以下操作
 */

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType   
{  
        NSURL *url = [request URL];
	    NSString *errorReason=nil;
		NSString *query = [url fragment];
		if (!query) {
			query = [url query];
		}
		NSDictionary *params = [self parseURLParams:query];
		NSString *accessToken = [params valueForKey:@"access_token"];
	    
	
	   errorReason = [params valueForKey:@"error"];
	  [self errormsg:errorReason];
	
	
	   if (navigationType == UIWebViewNavigationTypeLinkClicked)//点击链接  
        { 
		  if (!accessToken) {
			errorReason = [params valueForKey:@"error"];
			BOOL userDidCancel = (!errorReason || [errorReason isEqualToString:@"login_denied"]);
			if(userDidCancel){
			    [self dialogDidCancel:query];
			} 		  
		} 
	   }
	  if (navigationType==UIWebViewNavigationTypeFormSubmitted) {//提交表单
		  NSDictionary *params = [self parseURLParams:query];
		  NSString *accessToken = [params valueForKey:@"access_token"];
		  if (accessToken) {
			  [self dialogDidSucceed:url];
		  }else {
			  errorReason = [params valueForKey:@"error"];
			  [self errormsg:errorReason];
		  }
	  }
    return YES;  
} 

-(void) errormsg:(NSString*) errorReason{
	if (errorReason) {
		if ([errorReason isEqualToString:@"expired_token"]) {
			NSLog(@"当前Token已过期。");
		}else if ([errorReason isEqualToString:@"invalid_request"]) {
			NSLog(@"请求缺少某个必需参数，包含一个不支持的参数或参数值，或者格式不正确。");
		}else if ([errorReason isEqualToString:@"invalid_client"]) {
			NSLog(@"无效的client_id");
		}else if ([errorReason isEqualToString:@"unauthorized_client"]) {
			NSLog(@"客户端没有权限申请该“response_type”对应的Access Grant。");
		}else if ([errorReason isEqualToString:@"access_denied"]) {
			NSLog(@"用户或授权服务器拒绝了请求。");
		}else if ([errorReason isEqualToString:@"unsupported_response_type"]) {
			NSLog(@"response_type 不为授权服务器所支持。");
		}else if ([errorReason isEqualToString:@"invalid_scope"]) {
			NSLog(@"请求的 scope 参数是无效的、未知的，或格式不正确的。");
		}else if ([errorReason isEqualToString:@"invalid_grant"]) {
			NSLog(@"提供的Access Grant是无效的、过期的或已撤销的");
		}else if ([errorReason isEqualToString:@"unsupported_grant_type"]) {
			NSLog(@"grant_type 不为授权服务器所支持。");
		}else {
			NSLog(@"未知的网络错误,关闭或是其它原因");
		}
	}}
@end
